<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
  </pageHeader>
  <div>
    <a-tabs @change="searchState" v-model:active-key="selectState" type="line">
      <a-tab-pane :key="0" title="全部"> </a-tab-pane>
      <a-tab-pane :key="1" title="待发货"> </a-tab-pane>
      <a-tab-pane :key="2" title="运输中"> </a-tab-pane>
      <a-tab-pane :key="3" title="已归档"> </a-tab-pane>
    </a-tabs>
  </div>
  <div class="search-box">
    <div>
      <a-space>
        <a-input-group>
          <!-- <a-select
            :style="{ width: '120px' }"
            placeholder="请选择"
            v-model="currSelectVal"
            :default-value="currSelectVal"
          >
            <a-option value="invoiceNumber"></a-option>
          </a-select> -->
          <a-input-search
            search-button
            :style="{ width: 'auto' }"
            placeholder="请输入发货单编号"
            v-model="currSelectSearch"
            @search="search"
          />
        </a-input-group>
        <a-button type="outline" @click="reset">
          <template #icon>
            <icon-refresh />
          </template>
          <template #default>重置</template>
        </a-button>
      </a-space>
    </div>
    <div>
      <a-space>
        <a-button status="success">
          <template #icon>
            <icon-download />
          </template>
          <template #default>导入</template>
        </a-button>

        <a-button status="warning">
          <template #icon>
            <icon-export rotate="-90" />
          </template>
          <template #default>导出</template>
        </a-button>

        <a-button type="primary" @click="showFormHeaderSetting"
          >表头设置</a-button
        >
      </a-space>
    </div>
  </div>
  <div style="padding: 10px">
    <tableTurn :tableData="getData" :args="args" ref="tableRef">
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.code"
        :title="item.name"
        :data-index="item.code"
        :width="150"
        align="center"
      >
        <template v-if="item.code === 'CreatedAt'" #cell="{ record }">
          {{ dayjs(record.CreatedAt).format('YYYY-MM-DD') }}
        </template>
      </a-table-column>
      <!-- 出库状态item -->
      <a-table-column
        fixed="right"
        :width="200"
        title="出库状态"
        align="center"
      >
        <template #cell>
          <a-typography-text type="success"> 已出库 </a-typography-text>
        </template>
      </a-table-column>
      <!-- 交货状态item -->
      <a-table-column
        fixed="right"
        :width="150"
        title="交货状态"
        align="center"
      >
        <template #cell="{ record }">
          <div
            class="status"
            :style="{
              color: orderStatus.filter((ele) => ele.id === record.state)[0]
                ?.backgroundColor,
            }"
          >
            <p
              :style="{
                'background': orderStatus.filter(
                  (ele) => ele.id === record.state
                )[0]?.backgroundColor,
                'box-shadow': `0px 0px 5px`,
              }"
            ></p>
            {{ orderStatus.filter((ele) => ele.id === record.state)[0]?.value }}
          </div></template
        >
      </a-table-column>
      <!-- 操作item -->
      <a-table-column :width="200" fixed="right" title="操作" align="center">
        <template #title> 操作 </template>
        <template #cell="{ record }">
          <a-tooltip v-if="record.state === 1" content="确认发货">
            <IconFont
              type="icon-zhanjuzulin"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDeliveryDetails(record.id)"
            />
          </a-tooltip>
          <a-space v-if="record.state === 2">
            <a-tooltip content="确认签收">
              <IconFont
                type="icon-a-16-querenqianshou1x"
                :size="26"
                :style="{
                  marginRight: '10px',
                  cursor: 'pointer',
                }"
                @click="goDeliveryDetails(record.id, 2)"
              />
            </a-tooltip>
            <a-tooltip content="更多功能">
              <a-dropdown>
                <IconFont
                  type="icon-more-def"
                  :size="26"
                  :style="{
                    marginRight: '10px',
                    cursor: 'pointer',
                  }"
                />
                <template #content>
                  <a-doption @click="goDeliveryDetails(record.id, 'details')"
                    >查看详情</a-doption
                  >
                  <a-doption @click="goDeliveryDetails(record.id, 4)"
                    >异常签收</a-doption
                  >
                  <a-doption @click="goDeliveryDetails(record.id, 5)"
                    >客户拒签</a-doption
                  >
                </template>
              </a-dropdown>
            </a-tooltip>
          </a-space>

          <a-tooltip
            v-if="
              record.state === 3 || record.state === 4 || record.state === 5
            "
            content="查看详情"
          >
            <IconFont
              type="icon-details-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer',
              }"
              @click="goDeliveryDetails(record.id, 'details')"
            />
          </a-tooltip>

          <!-- <a-popconfirm content="确认删除?" type="error" @ok="del(record.id)">
              <a-button type="text" status="danger">删除</a-button>
            </a-popconfirm> -->
        </template>
      </a-table-column>
    </tableTurn>
  </div>
  <FormHeaderSetting
    v-model:visible="formHeaderSettingVisible"
    title="销售发货列表表头设置"
    :resultList="headerSetting.list"
    @headerSave="headerSave"
  ></FormHeaderSetting>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed, onMounted, watchEffect } from 'vue';
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import { getInvoiceAll } from '@/api/inventory-management/outbound-management/sales-shipment-outbound/sales-shipment/index';
  import {
    getHeader,
    PostHeader,
  } from '@/api/inventory-management/header-management/index';

  const selectState = ref();
  const router = useRouter();
  const title: string = '销售发货';
  const breadCrumb: string[] = [
    '库存管理',
    '出库管理',
    '销售发货出库',
    '销售发货',
  ];
  const modelVisible = ref(false);
  const formHeaderSettingVisible = ref(false);
  let tableRef: any = ref(); // 储存table的ref
  let currSelectVal = ref(); // 储存当前下拉选择框的值
  let currSelectSearch = ref(''); // 储存下拉选择框对应的搜索框的值
  const modelCauseVisible = ref(false);
  const userState = ref();
  const beginTime = ref();
  const endTime = ref();
  const ownList = ref();
  const saveUserId = ref<any>(
    JSON.parse(sessionStorage.getItem('loginInfo') as any)
  );
  const ShipmentId = ref();
  // <a-typography-text disabled v-if="record.state === 1">
  //           待发货
  //         </a-typography-text>
  //         <a-typography-text type="primary" v-if="record.state === 2">
  //           运输中
  //         </a-typography-text>
  //         <a-typography-text type="success" v-if="record.state === 3">
  //           已完成
  //         </a-typography-text>
  //         <a-typography-text type="warning" v-if="record.state === 4">
  //           异常签收
  //         </a-typography-text>
  //         <a-typography-text type="danger" v-if="record.state === 5">
  //           客户拒签
  //         </a-typography-text>
  const orderStatus = [
    { id: 1, value: '待发货', backgroundColor: '#cccccc' },
    { id: 2, value: '运输中', backgroundColor: '#3d7eff' },
    { id: 3, value: '已完成', backgroundColor: '#009933' },
    { id: 4, value: '异常签收', backgroundColor: '#ff0000' },
    { id: 5, value: '客户拒签', backgroundColor: '#ff9900' },
  ];

  // 表格配置
  const args = reactive({
    stripe: true,
    // rowSelection: {
    //   type: 'checkbox',
    //   showCheckedAll: true,
    //   onlyCurrent: false,
    // },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  // 储存表头数据
  const priorityData = ref(); // 储存搜索优先级的值
  const headerSetting = reactive<any>({
    list: [],
  });

  const getData = async (page: any) => {
    try {
      const msg: any = {};
      if (currSelectSearch.value) msg.number = currSelectSearch.value;
      if (selectState.value) msg.state = selectState.value;
      if (priorityData.value) msg.priority = priorityData.value;
      if (ownList.value) msg.ownList = ownList.value;
      if (beginTime.value) msg.beginTime = beginTime.value;
      if (endTime.value) msg.endTime = endTime.value;
      let res = await getInvoiceAll({
        ...page,
        ...msg,
        type: 1,
      });

      if (res.content === null || res.content === undefined) {
        res.content = [];
      }

      res.content.map((item: any) => {
        item.show = false;
        return item;
      });

      return Promise.resolve(res);
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const columns = [
    {
      code: 'number',
      isDefault: 1,
      name: '销售发货单号',
    },
    {
      code: 'outboundNumber',
      isDefault: 1,
      name: '关联销售出库单号',
    },
    {
      code: 'orderNumber',
      isDefault: 1,
      name: '关联销售订单号',
    },
    {
      code: 'CreatedAt',
      isDefault: 1,
      name: '出库单下达时间',
    },
    // {
    //   code: 'userStaffName',
    //   isDefault: 1,
    //   name: '确认出库时间',
    // },
    // {
    //   code: 'outboundDate',
    //   isDefault: 1,
    //   name: '计划出货日期',
    // },
    {
      code: 'consigneeName',
      isDefault: 1,
      name: '客户名称',
    },

    {
      code: 'userStaffName',
      isDefault: 1,
      name: '业务员',
    },
    // {
    //   code: 'consigneeAddress',
    //   isDefault: 1,
    //   name: '计划出货时间',
    // },

    {
      code: 'consigneeName',
      isDefault: 1,
      name: '收货人',
    },
  ];

  const showFormHeaderSetting = () => {
    formHeaderSettingVisible.value = true;
  };

  const headerSettingData = async () => {
    try {
      const res = await getHeader({
        userId: saveUserId.value.id,
        listType: 6,
      });
      headerSetting.list = res.extends ? res.extends : columns;
    } catch (err: unknown) {
      console.log(err);
    }
  };
  headerSettingData();

  const reset = () => {
    currSelectVal.value = '';
    currSelectSearch.value = '';
    priorityData.value = undefined;
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const searchState = (val: number) => {
    reset();
  };
  const search = (val: number) => {
    tableRef.value.refreshPaging();
    tableRef.value.loadData();
  };

  const headerSave = async (val: any) => {
    try {
      const data = {
        userId: saveUserId.value.id,
        listType: 6,
        extend: JSON.stringify(val),
      };
      await PostHeader(data);
      headerSetting.list = [...val];
    } catch (err: unknown) {
      console.log(err);
    }
  };

  const addOutbound = (e?: number) => {
    router.push({
      name: 'AddSalesOutbound',
    });
  };

  // 在表格上显示的表头
  const selectedHeader = computed(() => {
    const arr: any = [];
    headerSetting.list.forEach((item: any) => {
      if (item.isDefault === 1) {
        arr.push(item);
      }
    });
    return arr;
  });

  // const del = async (id: number) => {
  //   await delWarehouseEntry({ id });
  //   tableRef.value.loadData();
  // };

  const setShipment = (id: number) => {
    modelVisible.value = true;
    ShipmentId.value = id;
  };

  const goDeliveryDetails = async (id: number, state?: number | string) => {
    if (!state) {
      router.push({
        name: 'ShipmentDetails',
        query: { id },
      });
    } else {
      router.push({
        name: 'ShipmentDetails',
        query: { id, state },
      });
    }
  };

  watchEffect(() => {
    if (modelVisible.value) {
      tableRef.value.loadData();
    }
  });
</script>

<style scoped lang="less">
  // .content-head {
  // }
  .search-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0px 10px;
  }

  :deep(.arco-space-item) {
    margin-top: 10px;
  }
  .Detail-item {
    cursor: pointer;
  }

  :deep(.arco-tabs-content) {
    padding-top: 0px;
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: center;

    p {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
</style>
